package ca.concordia.soen6461.wichf.controller;

import java.util.List;

import ca.concordia.soen6461.wichf.controller.dsl.NavigationEdge;
import ca.concordia.soen6461.wichf.controller.dsl.NavigationModel;
import ca.concordia.soen6461.wichf.controller.dsl.ViewNode;

public class Controller {

	private NavigationModel navigationModel;
	
	public Controller(NavigationModel navigationModel) {
		this.navigationModel = navigationModel;
	}
	
	public View<?> handle(Event event) {
		ViewStack viewStack = event.getSession().getViewStack();
		if (viewStack.isEmpty()) {
			viewStack.goTo(navigationModel.getHomeViewNode().getView());
		} else {
			ViewNode<?> node = navigationModel.getViewNode(viewStack.currentView());
			List<NavigationEdge> edges = node.getNavigationEdges();
			NavigationEdge edge = selectEdge(event, edges);
			if (edge != null) {
				edge.getAction().perform(event);
				edge.getNavigation().navigate(viewStack);
			}
		}
		return viewStack.currentView();
	}

	private NavigationEdge selectEdge(Event event, List<NavigationEdge> edges) {
		NavigationEdge edge = null;
		for (NavigationEdge e : edges) {
			if (e.getEvent() == event.getClass() && e.getCondition().evaluate(event)) {
				edge = e;
				break;
			}
		}
		return edge;
	}
	
}
